const app = getApp()
var websocket = require('../../utils/websocket.js');
var utils = require('../../utils/util.js');
const {
  $Toast
} = require('../../dist/base/index');
var interval;

Page({
  data: {
    newslist: [],
    userInfo: {},
    scrollTop: 0,
    increase: false, //图片添加区域隐藏
    aniStyle: true, //动画效果
    message: "",
    previewImgList: [],
    tip: '文件发送中...',
    loading: false,
		emoji: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35'],
		emojiChar: '😓-😡-😳-😁-😠-😪-😄-😄-😔-😒-😞-😖-😏-😥-😷-😚-😂-😉-😵-☺-😌-😣-😥-😭-😱-😰-😨-😍-😃-😊-😝-😋-🍓-☀-☁-☔',
		emojiFlag: false,
		isEmpty: true,
		markers: [],
		polyline: [],
		controls: [{
			id: 1,
			iconPath: '/images/location.png',
			position: {
				left: 0,
				top: 300 - 50,
				width: 50,
				height: 50
			},
			clickable: false
		}],
		locationFlag: true
  },

  onLoad: function() {
    var that = this;

    var chatInfo = wx.getStorageSync("chatInfo");

    if (!chatInfo) {
      $Toast({
        content: '请先登录!',
        type: 'error'
      });
      wx.reLaunch({
        url: '/pages/userinfo/userinfo',
      });
    } else {
      this.setData({
        chatInfo: chatInfo
      });

      if (chatInfo.friendInfo.rename) {
        wx.setNavigationBarTitle({
          title: chatInfo.friendInfo.rename
        });
      } else {
        wx.setNavigationBarTitle({
          title: chatInfo.friendInfo.username
        });
      }

      websocket.connect(this.data.chatInfo, function(res) {
        if (JSON.parse(res.data).data.length == 0) {
          that.setData({
            newslist: []
          });
        } else {
          var data = JSON.parse(res.data).data;
					var marker = [];
					var polyline = [];
          
          for (var i = 0; i < data.length; i++) {
						if(i == 0) {
							data[i].flagtime = true;
						} else {
							var currenttime = new Date(data[i].created_date).getTime();
							var begintime = new Date(data[i - 1].created_date).getTime();
							currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
						}

						if (data[i].chat_type == 3) {
							data[i].content = JSON.parse(data[i].content);
							data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

							marker.push([{
								iconPath: "/images/location.png",
								id: i,
								latitude: data[i].content.latitude,
								longitude: data[i].content.longitude,
								width: 50,
								height: 50,
							}]);

							polyline.push([{
								points: [{
									latitude: data[i].content.latitude,
									longitude: data[i].content.longitude
								}],
								color: "#FF0000DD",
								width: 2,
								dottedLine: true
							}]);
						}

						if (data[i].chat_type == 4) {
							data[i].content = JSON.parse(data[i].content);
							data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
						}
          }

          that.setData({
            newslist: data,
						markers: marker,
						polyline: polyline
          });

          that.bottom();
        }
      });
    }
  },

	locationTransfer: function (e) {
		var that = this;
		var onlineInfo = that.data.newslist[e.currentTarget.dataset.index];

		//获取当前定位，开启导航功能
		wx.getLocation({
			type: 'gcj02', 
			success: function (res) {
				var latitude = res.latitude;
				var longitude = res.longitude;

				wx.request({
					url: utils.basePath + '/article/v1/locationToAddr',
					method: 'post',
					data: {
						location: latitude + ',' + longitude
					},
					header: {
						'content-type': 'application/json'
					},
					success(res) {
						if (res.data.payload.status == 0) {
							var mapInfo = {
								now_location: {
									latitude: latitude,
									longitude: longitude,
									address: res.data.payload.result.address + res.data.payload.result.formatted_addresses.recommend
								},
								target_location: {
									latitude: onlineInfo.content.latitude,
									longitude: onlineInfo.content.longitude,
									address: onlineInfo.content.address
								}
							};

							setTimeout(function () {
								if (that.data.locationFlag) {
									wx.navigateTo({
										url: '/pages/mapdetail/mapdetail?mapInfo=' + JSON.stringify(mapInfo),
									});
								}

								that.setData({ locationFlag: true });
							}, 1000);
						} else {
							$Toast({
								content: res.data.payload.message,
								type: 'error'
							});
						}
					},
					fail(err) {
						console.log(err);
					}
				});
			}
		});
	},

	emoji: function() {
		this.setData({ emojiFlag: !this.data.emojiFlag, increase: false});
	},

	onHide: function() {
		clearInterval(interval);
	},

  getIntervalChat: function(that) {
    interval = setInterval(function() {
      wx.closeSocket();
      websocket.connect(that.data.chatInfo, function(res) {
        if (JSON.parse(res.data).data.length == 0) {
          that.setData({
            newslist: []
          });
        } else {
					var data = JSON.parse(res.data).data;
					var marker = [];
					var polyline = [];

					for (var i = 0; i < data.length; i++) {
						if (i == 0) {
							data[i].flagtime = true;
						} else {
							var currenttime = new Date(data[i].created_date).getTime();
							var begintime = new Date(data[i - 1].created_date).getTime();
							currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
						}

						if (data[i].chat_type == 3) {
							data[i].content = JSON.parse(data[i].content);
							data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

							marker.push([{
								iconPath: "/images/location.png",
								id: i,
								latitude: data[i].content.latitude,
								longitude: data[i].content.longitude,
								width: 50,
								height: 50
							}]);

							polyline.push([{
								points: [{
									latitude: data[i].content.latitude,
									longitude: data[i].content.longitude
								}],
								color: "#FF0000DD",
								width: 2,
								dottedLine: true
							}]);
						}

						if (data[i].chat_type == 4) {
							data[i].content = JSON.parse(data[i].content);
							data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
						}
					}

					that.setData({
						newslist: data,
						markers: marker,
						polyline: polyline
					});
        }
      });
    }, 5000);
  },

  // 页面卸载
  onUnload() {
    var that = this;
    clearInterval(interval);

    //将消息设置为已读
    wx.request({
      url: utils.basePath + '/article/v1/changeChatType',
      method: "post",
      data: {
        myphone: that.data.chatInfo.userInfo.account,
        app_sid: that.data.chatInfo.userInfo.app_sid,
        friendphone: that.data.chatInfo.friendInfo.account
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          wx.reLaunch({
            url: '/pages/friend/friend',
            success: function(res) {
              wx.closeSocket(function(res) {
                $Toast({
                  content: '连接已断开!',
                  type: 'error'
                });
              });
            },
          });
        } 
      }
    });
  },


	authorPage: function () {
		wx.navigateTo({
			url: '/pages/authorpage/authorpage',
		})
	},

	onShow: function() {
		this.getIntervalChat(this);
	},

	openDocument: function(e) {
		wx.downloadFile({
			url: e.currentTarget.dataset.path,
			success: function (res) {
				wx.openDocument({
					filePath: res.tempFilePath,
					success: function (res) {
						console.log('打开文档成功');
					}
				});
			}
		});
	},

	longEvent: function(e) {
		var that = this;
		that.setData({locationFlag: false});
		var index = e.currentTarget.dataset.index;
		var itemList = [];

		if(that.data.newslist[index].chat_type == 0) {
			itemList.push('复制');
		}

		if (that.data.newslist[index].chat_type == 2) {
			itemList.push('保存');
		}

		itemList.push('收藏');
		itemList.push('删除');

		wx.showActionSheet({
			itemList: itemList,
			success: function (res) {
				//文本复制
				if (that.data.newslist[index].chat_type == 0 && res.tapIndex == 0) { 
					//取到对应的文本值，调用copyMessage()
					that.copyMessage(that.data.newslist[index].content);
				} else if (that.data.newslist[index].chat_type == 2 && res.tapIndex == 0) {
					//视频长按保存
					that.saveVideo(that.data.newslist[index].content);
				} else if ((that.data.newslist[index].chat_type == 0 && res.tapIndex == 1) || (that.data.newslist[index].chat_type == 2 && res.tapIndex == 1) || (that.data.newslist[index].chat_type != 0 && that.data.newslist[index].chat_type != 2 && res.tapIndex == 0)) {
					//根据不同的chat_type存储不同格式的值
					that.collectMessage(that.data.newslist[index]);
				} else if ((that.data.newslist[index].chat_type == 0 && res.tapIndex == 2) || (that.data.newslist[index].chat_type == 2 && res.tapIndex == 2) || (that.data.newslist[index].chat_type != 0 && that.data.newslist[index].chat_type != 2 && res.tapIndex == 1)) {
					//删除本条聊天记录
					that.deleteOnlineChat(that.data.newslist[index].id);
				}
			},
			fail: function (res) {
				console.log(res.errMsg);
			}
		});
	},

	deleteOnlineChat: function(id) {
		var that = this;

		wx.request({
			url: utils.basePath + '/article/v1/deleteOnlineMessage',
			method: 'post',
			data: {
				id: id
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status == 200) {
					$Toast({
						content: res.data.payload,
						type: 'success'
					});
				} else {
					$Toast({
						content: res.data.err,
						type: 'error'
					});
				}
			}
		});
	},

	collectMessage: function(onlineInfo) {
		var that = this;

		wx.request({
			url: utils.basePath + '/article/v1/saveCollectMessage',
			method: 'post',
			data: {
				account: that.data.chatInfo.userInfo.account,
				app_sid: that.data.chatInfo.userInfo.app_sid, 
				openid: that.data.chatInfo.userInfo.openid,
				content: onlineInfo.chat_type > 2 ? JSON.stringify(onlineInfo.content) : onlineInfo.content,
				chat_type: onlineInfo.chat_type,
				send_user: onlineInfo.username
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status == 200) {
					$Toast({
						content: '收藏成功!',
						type: 'success'
					});
				} else {
					$Toast({
						content: res.data.err,
						type: 'error'
					});
				}
			}
		});
	},

	copyMessage: function (content) {
		//复制消息
		wx.setClipboardData({
			data: content,
			success: function (res) {
				console.log('内容成功复制!');
			}
		});
	},

  send: function() {
    var that = this;

    if (that.data.message.trim() == "") {
      $Toast({
        content: '不能发送空消息!',
        type: 'error'
      });
    } else {
      that.setData({
        increase: false,
				emojiFlag: false
      });

      //封装聊天记录参数
      var chatInfo = that.data.chatInfo;
      chatInfo.chat_content = that.data.message;
      chatInfo.chat_type = 0;
      chatInfo = JSON.stringify(chatInfo);

      websocket.send(chatInfo);

      //接受服务器消息
      wx.onSocketMessage(function(res) {
				var data = JSON.parse(res.data).data;
				var marker = [];
				var polyline = [];

				for (var i = 0; i < data.length; i++) {
					if (i == 0) {
						data[i].flagtime = true;
					} else {
						var currenttime = new Date(data[i].created_date).getTime();
						var begintime = new Date(data[i - 1].created_date).getTime();
						currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
					}

					if (data[i].chat_type == 3) {
						data[i].content = JSON.parse(data[i].content);
						data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

						marker.push([{
							iconPath: "/images/location.png",
							id: i,
							latitude: data[i].content.latitude,
							longitude: data[i].content.longitude,
							width: 50,
							height: 50
						}]);

						polyline.push([{
							points: [{
								latitude: data[i].content.latitude,
								longitude: data[i].content.longitude
							}],
							color: "#FF0000DD",
							width: 2,
							dottedLine: true
						}]);
					}

					if (data[i].chat_type == 4) {
						data[i].content = JSON.parse(data[i].content);
						data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
					}
				}

				that.setData({
					newslist: data,
					markers: marker,
					polyline: polyline,
					message: ''
				});

        that.bottom();
      });
    }
  },

  //监听input值的改变
  bindChange(res) {
		if (!res.detail.value) {
			this.setData({
				isEmpty: true,
				emojiFlag: false,
				increase: false
			});
		} else {
			this.setData({
				message: res.detail.value,
				isEmpty: false,
				emojiFlag: false,
				increase: false
			});
		}
  },

  cleanInput() {
    this.setData({
      message: this.data.message
    })
  },

	emojiChoose: function (e) {
		var index = e.target.dataset.id;
		var emojiArr = this.data.emojiChar.split('-');
		this.setData({
			message: this.data.message + emojiArr[index],
			isEmpty: false
		});
	},

  increase() {
    this.setData({
      increase: !this.data.increase,
      aniStyle: true,
			emojiFlag: false
    })
  },

  outbtn() {
    this.setData({
      increase: false,
      aniStyle: true,
			emojiFlag: false
    });
  },

  //发送图片
  chooseImage() {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        var tempFilePaths = res.tempFilePaths;

        that.setData({
          loading: true,
          increase: false
        });

        wx.uploadFile({
          url: utils.basePath + '/users/upload_avatar',
          filePath: tempFilePaths[0],
          name: 'avatar',
          headers: {
            'Content-Type': 'form-data'
          },

          success: function(res) {
            that.setData({
              loading: false
            });

            var result = JSON.parse(res.data);
            if (result.status == 200) {
              //上传图片操作
              var chatInfo = that.data.chatInfo;
              chatInfo.chat_content = result.payload.avatar_path;
              chatInfo.chat_type = 1;
              chatInfo = JSON.stringify(chatInfo);

              websocket.send(chatInfo);

              //接受服务器消息
              wx.onSocketMessage(function(res) {
								var data = JSON.parse(res.data).data;
								var marker = [];
								var polyline = [];

								for (var i = 0; i < data.length; i++) {
									if (i == 0) {
										data[i].flagtime = true;
									} else {
										var currenttime = new Date(data[i].created_date).getTime();
										var begintime = new Date(data[i - 1].created_date).getTime();
										currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
									}

									if (data[i].chat_type == 3) {
										data[i].content = JSON.parse(data[i].content);
										data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

										marker.push([{
											iconPath: "/images/location.png",
											id: i,
											latitude: data[i].content.latitude,
											longitude: data[i].content.longitude,
											width: 50,
											height: 50
										}]);

										polyline.push([{
											points: [{
												latitude: data[i].content.latitude,
												longitude: data[i].content.longitude
											}],
											color: "#FF0000DD",
											width: 2,
											dottedLine: true
										}]);
									}

									if (data[i].chat_type == 4) {
										data[i].content = JSON.parse(data[i].content);
										data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
									}
								}

								that.setData({
									newslist: data,
									markers: marker,
									polyline: polyline
								});

                that.bottom();
              });
            } else {
              $Toast({
                content: result.err,
                type: 'error'
              });
            }
          }
        });
      }
    });
  },

  //发送视频
  chooseVideo() {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        var tempFilePaths = res.tempFilePath;

        that.setData({
          loading: true,
          increase: false
        });

        wx.uploadFile({
          url: utils.basePath + '/users/upload_video',
          filePath: tempFilePaths,
          name: 'mp4_url',
          headers: {
            'Content-Type': 'form-data'
          },

          success: function(res) {
            if (res.statusCode == 413) {
              that.setData({
                loading: false
              });

              $Toast({
                content: '视频过大，请重新上传',
                type: 'error'
              });
            } else {
              that.setData({
                loading: false
              });

              var result = JSON.parse(res.data);
              if (result.status == 200) {
                //上传视频操作
                var chatInfo = that.data.chatInfo;
                chatInfo.chat_content = result.payload;
                chatInfo.chat_type = 2;
                chatInfo = JSON.stringify(chatInfo);

                websocket.send(chatInfo);

                //接受服务器消息
                wx.onSocketMessage(function(res) {
									var data = JSON.parse(res.data).data;
									var marker = [];
									var polyline = [];

									for (var i = 0; i < data.length; i++) {
										if (i == 0) {
											data[i].flagtime = true;
										} else {
											var currenttime = new Date(data[i].created_date).getTime();
											var begintime = new Date(data[i - 1].created_date).getTime();
											currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
										}

										if (data[i].chat_type == 3) {
											data[i].content = JSON.parse(data[i].content);
											data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

											marker.push([{
												iconPath: "/images/location.png",
												id: i,
												latitude: data[i].content.latitude,
												longitude: data[i].content.longitude,
												width: 50,
												height: 50
											}]);

											polyline.push([{
												points: [{
													latitude: data[i].content.latitude,
													longitude: data[i].content.longitude
												}],
												color: "#FF0000DD",
												width: 2,
												dottedLine: true
											}]);
										}

										if (data[i].chat_type == 4) {
											data[i].content = JSON.parse(data[i].content);
											data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
										}
									}

									that.setData({
										newslist: data,
										markers: marker,
										polyline: polyline
									});

                  that.bottom();
                });
              } else {
                $Toast({
                  content: result.err,
                  type: 'error'
                });
              }
            }
          }
        });
      }
    });
  },

  //视频保存到本地
  saveVideo: function(content) {
    var that = this;

		//弹出对话框
		wx.showModal({
			title: '警告',
			content: '确定保存到本地?',
			success: function (res) {
				if (res.confirm) {
					wx.getSetting({
						success(res) {
							if (!res.authSetting['scope.writePhotosAlbum']) {
								wx.authorize({
									scope: 'scope.writePhotosAlbum',
									success() {
										console.log('授权成功!');
									}
								});
							}

							that.setData({
								loading: true,
								tip: '视频下载中...'
							});

							//先下载文件获得临时路径
							wx.downloadFile({
								url: content,
								success: function (res) {
									that.setData({
										loading: false,
										tip: '加载中...'
									});

									if (res.statusCode == 200) {
										wx.saveVideoToPhotosAlbum({
											filePath: res.tempFilePath,
											
											success(res) {
												$Toast({
													content: '视频保存成功',
													type: 'success'
												});
											},

											fail(err) {
												$Toast({
													content: '视频保存失败!',
													type: 'error'
												});
											}
										});
									} else {
										$Toast({
											content: '视频下载异常!',
											type: 'error'
										});
									}
								}
							});
						}
					});
				} 
			}
		});
  },

	chooseFile: function() {
		var that = this;
		that.setData({ emojiFlag: false, increase: false });

		wx.chooseMessageFile({
			count: 1,
			type: 'file',
			success(res) {
				var tempFiles = res.tempFiles[0];

				that.setData({
					loading: true
				});

				wx.uploadFile({
					url: utils.basePath + '/users/upload_video',
					filePath: tempFiles.path,
					name: 'mp4_url',
					headers: {
						'Content-Type': 'form-data'
					},

					success: function (res) {
						if (res.statusCode == 413) {
							that.setData({
								loading: false
							});

							$Toast({
								content: '视频过大，请重新上传',
								type: 'error'
							});
						} else {
							that.setData({
								loading: false
							});

							var result = JSON.parse(res.data);
							if (result.status == 200) {
								//上传视频操作
								var chatInfo = that.data.chatInfo;
								chatInfo.chat_content = JSON.stringify({
									name: tempFiles.name,
									path: result.payload,
									size: tempFiles.size
								});
								chatInfo.chat_type = 4;
								chatInfo = JSON.stringify(chatInfo);

								websocket.send(chatInfo);

								//接受服务器消息
								wx.onSocketMessage(function (res) {
									var data = JSON.parse(res.data).data;
									var marker = [];
									var polyline = [];

									for (var i = 0; i < data.length; i++) {
										if (i == 0) {
											data[i].flagtime = true;
										} else {
											var currenttime = new Date(data[i].created_date).getTime();
											var begintime = new Date(data[i - 1].created_date).getTime();
											currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
										}

										if (data[i].chat_type == 3) {
											data[i].content = JSON.parse(data[i].content);
											data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

											marker.push([{
												iconPath: "/images/location.png",
												id: i,
												latitude: data[i].content.latitude,
												longitude: data[i].content.longitude,
												width: 50,
												height: 50
											}]);

											polyline.push([{
												points: [{
													latitude: data[i].content.latitude,
													longitude: data[i].content.longitude
												}],
												color: "#FF0000DD",
												width: 2,
												dottedLine: true
											}]);
										}

										if (data[i].chat_type == 4) {
											data[i].content = JSON.parse(data[i].content);
											data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
										}
									}

									that.setData({
										newslist: data,
										markers: marker,
										polyline: polyline
									});

									that.bottom();
								});
							} else {
								$Toast({
									content: result.err,
									type: 'error'
								});
							}
						}
					}
				});
			}
		})
	},

	chooseLocation: function() {
		var that = this;
		that.setData({emojiFlag: false, increase: false});
		wx.getLocation({
			type: 'gcj02', //返回可以用于wx.openLocation的经纬度
			success: function (res) {
				var latitude = res.latitude//维度
				var longitude = res.longitude//经度

				wx.request({
					url: utils.basePath + '/article/v1/locationToAddr',
					method: 'post',
					data: {
						location: latitude + ',' + longitude
					},
					header: {
						'content-type': 'application/json'
					},
					success(res) {
						if (res.data.payload.status == 0) {
							var locationInfo = {
								latitude: latitude,
								longitude: longitude,
								address: res.data.payload.result.address + res.data.payload.result.formatted_addresses.recommend
							};

							//发送地理位置消息
							var chatInfo = that.data.chatInfo;
							chatInfo.chat_content = JSON.stringify(locationInfo);
							chatInfo.chat_type = 3;
							chatInfo = JSON.stringify(chatInfo);
							websocket.send(chatInfo);

							//接受服务器消息
							wx.onSocketMessage(function (res) {
								var data = JSON.parse(res.data).data;
								var marker = [];
								var polyline = [];

								for (var i = 0; i < data.length; i++) {
									if (i == 0) {
										data[i].flagtime = true;
									} else {
										var currenttime = new Date(data[i].created_date).getTime();
										var begintime = new Date(data[i - 1].created_date).getTime();
										currenttime - begintime > 1000 * 60 ? data[i].flagtime = true : data[i].flagtime = false;
									}

									if (data[i].chat_type == 3) {
										data[i].content = JSON.parse(data[i].content);
										data[i].content.addr = data[i].content.address.substring(0, 9) + '...';

										marker.push([{
											iconPath: "/images/location.png",
											id: i,
											latitude: data[i].content.latitude,
											longitude: data[i].content.longitude,
											width: 50,
											height: 50
										}]);

										polyline.push([{
											points: [{
												latitude: data[i].content.latitude,
												longitude: data[i].content.longitude
											}],
											color: "#FF0000DD",
											width: 2,
											dottedLine: true
										}]);
									}

									if (data[i].chat_type == 4) {
										data[i].content = JSON.parse(data[i].content);
										data[i].content.size = (data[i].content.size / 1000).toFixed(1) + ' k';
									}
								}

								that.setData({
									newslist: data,
									markers: marker,
									polyline: polyline
								});

								that.bottom();
							});
						} else {
							$Toast({
								content: res.data.payload.message,
								type: 'error'
							});
						}
					},
					fail(err) {
						console.log(err);
					}
				});
			}
		});
	},

  //图片预览
  previewImg(e) {
    var that = this;
    var res = e.target.dataset.src;
    var list = this.data.previewImgList;
    
    if (list.indexOf(res) == -1) {
      this.data.previewImgList.push(res);
    }

    wx.previewImage({
      current: res, 
      urls: that.data.previewImgList 
    });
  },

  //聊天消息始终显示最底端
  bottom: function() {
    var query = wx.createSelectorQuery();
    query.select('#flag').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec(function(res) {
      wx.pageScrollTo({
        scrollTop: res[1].scrollHeight // #the-id节点的下边界坐标
      });
      res[1].scrollTop; // 显示区域的竖直滚动位置
    })
  },
});